package research.sbookmarking.io;

//import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Random;

import org.connotea.Connotea;

import research.sbookmarking.DataContainer;
import research.sbookmarking.GeneralContainer;

//import java.util.Random;


public class RandomUserCommand extends BookmarkCommand {
	public RandomUserCommand(String queryName, List<String> command) {
		super(null,queryName,command);
	}

	public RandomUserCommand(String queryName, List<String> command, Integer limit, 
			 Integer start) {

		super(null, queryName,command, limit, start);
	}

	public RandomUserCommand(String filename, String queryName, List<String> command) {
		super(filename,queryName,command);
	}

	public RandomUserCommand(String filename, String queryName, List<String> command, Integer limit, 
							 Integer start) {
		
		super(filename, queryName,command, limit, start);
	}

/*
	private void add (ArrayList users, List list) {
		Iterator iterate = list.iterator();
		while (iterate.hasNext()){
			Object item = iterate.next();
			if (users.contains(item)!=true){
				users.add(users);
			}
		}
	}
*/
	private List<String> getUserList (){
		DataContainer temp = getResult();
		List<String> tempory = temp.getUniqueUsers();
		setResult(null);
		System.gc();
		//System.out.println ("\n\tNo of user: " + tempory.size() +"\n");
		return tempory;
	}
	
	/* (non-Javadoc)
	 * @see research.sbookmarking.input.BookmarkCommand#execute()
	 */
	@Override
	public void execute() {
		//this.setSaveResults(true);
		List<String> users;
		//String filename = getQueryFilename();
		String filename=this.getQueryFilename();
		System.out.println ("filename: " + filename);
		if (filename==null) {
			System.out.println ("First getting list then get users");
			super.execute();
			System.out.println ("Finished getting list now creating a list of users to retrieve");
			users = this.getUserList();
		}
		else {
			try {
				users = InputController.getInstance().readQueryList(filename,"DataInputStream");
			}
			catch (Exception x){
				users = InputController.getInstance().readQueryList(filename,"InputStream");
			}
		}
		
		setQueryName("User");
		OutputController oc = OutputController.getInstance();

		Connotea database = new Connotea ("alby1976","a1014leung");
		Random random = new Random();
		

		//ArrayList<Object> param = new ArrayList<Object>();
		
		DataContainer container = new GeneralContainer(this.getQueryName());
		ArrayList<String>queryed = new ArrayList<String>();
		int count=1;
		int totalQuery=0;
		String username = null;
		//HSSFWorkbook wb = null;
		String time = research.sbookmarking.process.util.StringUtils.convertIllegalChar(Calendar.getInstance().getTime()+"-");
		filename = time+getQueryName()+"-query.txt.gz";
		oc.writeDsvDataHeader("data/dsv/"+time+getQueryName()+".txt.gz", this.createNotes(), this.createHeader());
		
		do {
			try {
				do {
					username = users.get(random.nextInt(users.size()));
				}
				while (queryed.contains(username) && queryed.size()!=users.size());
				if (queryed.contains(username)){
					break;
				}
				
				queryed.add(username);
				
				System.out.println ("Getting data for "+username+"....");
				//wb = setupExcelFile(oc,username);
				//int temp = getAll(database, container, username, getLimit(), getStart(),wb, wb.getSheet(username),2);
				int temp = getAll(database, time+getQueryName(), username, getLimit(), getStart(),null, null,2);
				if (temp==0){
					count--;
					//wb = null;
				}
				else {
					oc.saveQuery(filename, "DataOutputStream", "data/raw/"+time+getQueryName()+"-"+username+"-posts-all.raw.gz", true);
					totalQuery+=temp;
					System.out.println ("Number of users retrieved: "+count+" Number of posting retrieved: "+totalQuery);
					count++;
/*
					try {
						String excelFile = "data/xls/"+username+"-"+convertIllegalChar(Calendar.getInstance().getTime()+"")+"-"+getQueryName()+".xls";
						oc.saveToExcel(excelFile, wb);
					} catch (IOException x) {
						// TODO Auto-generated catch block
						System.err.println (x.getMessage());

						Logger logger = AppController.getInstance().getLogger();
						logger.log(Level.FINEST,"Cause: " + x.getCause()+"");
						logger.log(Level.FINEST,Arrays.asList(x.getStackTrace()).toString());
						logger.log(Level.FINE,AppController.newline);
						
					}
*/
				}
			}
			catch (NullPointerException e){
				count--;
			}
			System.gc();
		}
		while ((totalQuery < 60000)&& (count <= users.size()));

		setResult(container);

		appendTimeline ("Data is from the beginning of Connotea.org to " + Calendar.getInstance().getTime()+".");

		oc.closeStream("DataOutputStream", filename);
		oc.closeStream("DataOutputStream", "data/dsv/"+time+getQueryName()+".txt.gz");
/*
		try{
			String excelFile = convertIllegalChar(Calendar.getInstance().getTime()+"")+"-"+getQueryName()+".xls";
			oc.writeExcelFile(excelFile, getTimeline(), container);
		}
		catch (java.io.IOException e){
			System.err.println ("IOException: " + e.getMessage());
		}
		//createUserQuery("randomUser.xml",results.iterator());
*/
	}
		
		
/*
		// get list of bookmarks
		super.execute();
		// get list of users
		ArrayList users = new ArrayList();
		Iterator lists = super.getResult().getQueryResults().iterator();
		while (lists.hasNext()) {
			this.add(users,((Post)lists.next()).getBookmark().getPostedBy());
		}
		
		ArrayList data = new ArrayList();
		Random random = new Random();
		
		try {
			Connotea database = new Connotea ("alby1976","a1014leung");
			ArrayList results = new ArrayList();
			for (int count=0; count <= this.numUsers;count++){
				//String user =(String)((List)getResult()).get(random.nextInt(users.size()));
				data.add(database.getBookmarks((String)users.get(random.nextInt(users.size()))));
			}
			setResult(new GeneralContainer(data));
		}
		catch (ConnoteaException e){
			System.err.println(e.getMessage());
			System.exit(-1);
		}
	}
*/
		
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
}
